package br.com.sig.business.model.entity;

import java.io.Serializable;

import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.BeanManager;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import javax.persistence.Version;

import br.com.sig.business.exception.BaseException;
import br.com.sig.business.model.entity.event.BeanManagerEvent;

@MappedSuperclass
public class BaseEntity implements Serializable {

	private static final long serialVersionUID = 4788813917978594591L;
	
	/*
	 * Identificador da entidade.
	 */
	private Long id;

	/*
	 * Version da entidade.
	 */
	private Long version;
	
	private static BeanManager beanManager;
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}
	
	@Column(nullable = false, columnDefinition = "bigint DEFAULT 0")
	@Version
	public Long getVersion() {
		return version;
	}

	public void setVersion(Long version) {
		this.version = version;
	}	
	
	@Transient
	public BeanManager getBeanManager() {
		return beanManager;
	}

	public void setBeanManager(@Observes BeanManagerEvent event) {
		beanManager = event.getBeanManager();
	}

	public void validate() throws BaseException {		
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		BaseEntity other = (BaseEntity) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}
	
	@Override
	public String toString() {
		return this.getClass().getName() + "[id=" + id + "]";
	}	
}